[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity } from '@growi/core';
  4. import type {
  5. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  6. } from '@growi/core';
  7. import {
  8. isClient, pagePathUtils, pathUtils,
  9. } from '@growi/core/dist/utils';
  10. import ExtensibleCustomError from 'extensible-custom-error';
  11. import type {
  12. GetServerSideProps, GetServerSidePropsContext,
  13. } from 'next';
  14. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  15. import dynamic from 'next/dynamic';
  16. import Head from 'next/head';
  17. import { useRouter } from 'next/router';
  18. import superjson from 'superjson';
  19. import { useEditorModeClassName } from '~/client/services/layout';
  20. import { PageView } from '~/components/Page/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsForbidden, useIsSharedUser,
  30. useIsEnabledStaleNotification, useIsIdenticalPath,
  31. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  32. useDefaultIndentSize, useIsIndentSizeForced,
  33. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  34. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  35. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  36. useEditorConfig, useIsAllReplyShown, useIsUploadAllFileAllowed, useIsUploadEnabled, useIsContainerFluid, useIsNotCreatable,
  37. } from '~/stores/context';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import {
  40. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  41. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  42. } from '~/stores/page';
  43. import { useRedirectFrom } from '~/stores/page-redirect';
  44. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  45. import { useSelectedGrant } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  50. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  51. import type { NextPageWithLayout } from './_app.page';
  52. import type { CommonProps } from './utils/commons';
  53. import {
  54. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  55. } from './utils/commons';
  56. declare global {
  57. // eslint-disable-next-line vars-on-top, no-var
  58. var globalEmitter: EventEmitter;
  59. }
  60. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  61. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  62. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  63. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  64. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  65. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  66. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  67. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  68. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  69. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  70. const logger = loggerFactory('growi:pages:all');
  71. const {
  72. isPermalink: _isPermalink, isCreatablePage,
  73. } = pagePathUtils;
  74. const { removeHeadingSlash } = pathUtils;
  75. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  76. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  77. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  78. {
  79. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  80. return v?.data != null
  81. && v?.data.toObject != null
  82. && v?.meta != null
  83. && isIPageInfoForEntity(v.meta);
  84. },
  85. serialize: (v) => {
  86. return {
  87. data: superjson.stringify(v.data.toObject()),
  88. meta: superjson.stringify(v.meta),
  89. };
  90. },
  91. deserialize: (v) => {
  92. return {
  93. data: superjson.parse(v.data),
  94. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  95. };
  96. },
  97. },
  98. 'IPageToShowRevisionWithMetaTransformer',
  99. );
  100. // GrowiContextualSubNavigation for NOT shared page
  101. type GrowiContextualSubNavigationProps = {
  102. isLinkSharingDisabled: boolean,
  103. }
  104. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  105. const { isLinkSharingDisabled } = props;
  106. const { data: currentPage } = useSWRxCurrentPage();
  107. return (
  108. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  109. );
  110. };
  111. type Props = CommonProps & {
  112. pageWithMeta: IPageToShowRevisionWithMeta | null,
  113. // pageUser?: any,
  114. redirectFrom?: string;
  115. // shareLinkId?: string;
  116. isLatestRevision?: boolean,
  117. isIdenticalPathPage?: boolean,
  118. isForbidden: boolean,
  119. isNotFound: boolean,
  120. isNotCreatable: boolean,
  121. // isAbleToDeleteCompletely: boolean,
  122. templateTagData?: string[],
  123. templateBodyData?: string,
  124. isSearchServiceConfigured: boolean,
  125. isSearchServiceReachable: boolean,
  126. isSearchScopeChildrenAsDefault: boolean,
  127. isEnabledMarp: boolean,
  128. isSlackConfigured: boolean,
  129. // isMailerSetup: boolean,
  130. isAclEnabled: boolean,
  131. // hasSlackConfig: boolean,
  132. drawioUri: string | null,
  133. noCdn: string,
  134. // highlightJsStyle: string,
  135. isAllReplyShown: boolean,
  136. isContainerFluid: boolean,
  137. editorConfig: EditorConfig,
  138. isEnabledStaleNotification: boolean,
  139. isEnabledAttachTitleHeader: boolean,
  140. // isEnabledLinebreaks: boolean,
  141. // isEnabledLinebreaksInComments: boolean,
  142. adminPreferredIndentSize: number,
  143. isIndentSizeForced: boolean,
  144. disableLinkSharing: boolean,
  145. skipSSR: boolean,
  146. ssrMaxRevisionBodyLength: number,
  147. grantData?: IPageGrantData,
  148. rendererConfig: RendererConfig,
  149. };
  150. const Page: NextPageWithLayout<Props> = (props: Props) => {
  151. // register global EventEmitter
  152. if (isClient() && window.globalEmitter == null) {
  153. window.globalEmitter = new EventEmitter();
  154. }
  155. const router = useRouter();
  156. useCurrentUser(props.currentUser ?? null);
  157. // commons
  158. useEditorConfig(props.editorConfig);
  159. useCsrfToken(props.csrfToken);
  160. useGrowiCloudUri(props.growiCloudUri);
  161. // page
  162. useIsContainerFluid(props.isContainerFluid);
  163. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  164. useIsForbidden(props.isForbidden);
  165. useIsNotCreatable(props.isNotCreatable);
  166. useRedirectFrom(props.redirectFrom ?? null);
  167. useIsSharedUser(false); // this page cann't be routed for '/share'
  168. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  169. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  170. useIsSearchPage(false);
  171. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  172. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  173. useIsSearchServiceReachable(props.isSearchServiceReachable);
  174. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  175. useIsSlackConfigured(props.isSlackConfigured);
  176. // useIsMailerSetup(props.isMailerSetup);
  177. useIsAclEnabled(props.isAclEnabled);
  178. // useHasSlackConfig(props.hasSlackConfig);
  179. // useNoCdn(props.noCdn);
  180. useDefaultIndentSize(props.adminPreferredIndentSize);
  181. useIsIndentSizeForced(props.isIndentSizeForced);
  182. useDisableLinkSharing(props.disableLinkSharing);
  183. useRendererConfig(props.rendererConfig);
  184. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  185. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  186. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  187. useIsAllReplyShown(props.isAllReplyShown);
  188. useIsUploadAllFileAllowed(props.editorConfig.upload.isUploadAllFileAllowed);
  189. useIsUploadEnabled(props.editorConfig.upload.isUploadEnabled);
  190. const { pageWithMeta } = props;
  191. const pageId = pageWithMeta?.data._id;
  192. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  193. const revisionBody = pageWithMeta?.data.revision?.body;
  194. useCurrentPathname(props.currentPathname);
  195. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  196. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  197. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  198. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  199. const { mutate: mutateIsNotFound } = useIsNotFound();
  200. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  201. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  202. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  203. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  204. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  205. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  206. useSetupGlobalSocket();
  207. useSetupGlobalSocketForPage(pageId);
  208. // Store initial data (When revisionBody is not SSR)
  209. useEffect(() => {
  210. if (!props.skipSSR) {
  211. return;
  212. }
  213. if (currentPageId != null && !props.isNotFound) {
  214. const mutatePageData = async() => {
  215. const pageData = await mutateCurrentPage();
  216. mutateEditingMarkdown(pageData?.revision.body);
  217. };
  218. // If skipSSR is true, use the API to retrieve page data.
  219. // Because pageWIthMeta does not contain revision.body
  220. mutatePageData();
  221. }
  222. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  223. // sync grant data
  224. useEffect(() => {
  225. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  226. mutateSelectedGrant(grantDataToApply);
  227. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  228. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  229. useEffect(() => {
  230. const decodedURI = decodeURI(window.location.pathname);
  231. if (isClient() && decodedURI !== props.currentPathname) {
  232. const { search, hash } = window.location;
  233. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  234. }
  235. }, [props.currentPathname, router]);
  236. // initialize mutateEditingMarkdown only once per page
  237. // need to include useCurrentPathname not useCurrentPagePath
  238. useEffect(() => {
  239. if (props.currentPathname != null) {
  240. mutateEditingMarkdown(revisionBody);
  241. }
  242. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  243. useEffect(() => {
  244. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  245. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  246. useEffect(() => {
  247. mutateCurrentPageId(pageId ?? null);
  248. }, [mutateCurrentPageId, pageId]);
  249. useEffect(() => {
  250. mutateIsNotFound(props.isNotFound);
  251. }, [mutateIsNotFound, props.isNotFound]);
  252. useEffect(() => {
  253. mutateIsLatestRevision(props.isLatestRevision);
  254. }, [mutateIsLatestRevision, props.isLatestRevision]);
  255. useEffect(() => {
  256. mutateTemplateTagData(props.templateTagData);
  257. }, [props.templateTagData, mutateTemplateTagData]);
  258. useEffect(() => {
  259. mutateTemplateBodyData(props.templateBodyData);
  260. }, [props.templateBodyData, mutateTemplateBodyData]);
  261. const title = generateCustomTitleForPage(props, pagePath);
  262. return (
  263. <>
  264. <Head>
  265. <title>{title}</title>
  266. </Head>
  267. <div className="dynamic-layout-root justify-content-between">
  268. <nav className="sticky-top">
  269. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  270. </nav>
  271. <DisplaySwitcher
  272. pageView={(
  273. <PageView
  274. pagePath={pagePath}
  275. initialPage={pageWithMeta?.data}
  276. rendererConfig={props.rendererConfig}
  277. />
  278. )}
  279. />
  280. <PageStatusAlert />
  281. </div>
  282. </>
  283. );
  284. };
  285. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  286. const editorModeClassName = useEditorModeClassName();
  287. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  288. };
  289. type LayoutProps = Props & {
  290. children?: ReactNode
  291. }
  292. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  293. // init sidebar config with UserUISettings and sidebarConfig
  294. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  295. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  296. };
  297. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  298. return (
  299. <>
  300. <GrowiPluginsActivator />
  301. <DrawioViewerScript />
  302. <Layout {...page.props}>
  303. {page}
  304. </Layout>
  305. <UnsavedAlertDialog />
  306. <DescendantsPageListModal />
  307. <DrawioModal />
  308. <HandsontableModal />
  309. <QuestionnaireModalManager />
  310. <TemplateModal />
  311. <LinkEditModal />
  312. <TagEditModal />
  313. </>
  314. );
  315. };
  316. function getPageIdFromPathname(currentPathname: string): string | null {
  317. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  318. }
  319. class MultiplePagesHitsError extends ExtensibleCustomError {
  320. pagePath: string;
  321. constructor(pagePath: string) {
  322. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  323. this.pagePath = pagePath;
  324. }
  325. }
  326. // apply parent page grant fot creating page
  327. async function applyGrantToPage(props: Props, ancestor: any) {
  328. await ancestor.populate('grantedGroups.item');
  329. const grant = {
  330. grant: ancestor.grant,
  331. };
  332. const grantedGroups = ancestor.grantedGroups ? {
  333. grantedGroups: ancestor.grantedGroups.map((group) => {
  334. return {
  335. id: group.item._id,
  336. name: group.item.name,
  337. type: group.type,
  338. };
  339. }),
  340. } : {};
  341. props.grantData = Object.assign(grant, grantedGroups);
  342. }
  343. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  344. const { model: mongooseModel } = await import('mongoose');
  345. const req: CrowiRequest = context.req as CrowiRequest;
  346. const { crowi } = req;
  347. const { revisionId } = req.query;
  348. const Page = crowi.model('Page') as PageModel;
  349. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  350. const { pageService, configManager } = crowi;
  351. let currentPathname = props.currentPathname;
  352. const pageId = getPageIdFromPathname(currentPathname);
  353. const isPermalink = _isPermalink(currentPathname);
  354. const { user } = req;
  355. if (!isPermalink) {
  356. // check redirects
  357. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  358. if (chains != null) {
  359. // overwrite currentPathname
  360. currentPathname = chains.end.toPath;
  361. props.currentPathname = currentPathname;
  362. // set redirectFrom
  363. props.redirectFrom = chains.start.fromPath;
  364. }
  365. // check whether the specified page path hits to multiple pages
  366. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  367. if (count > 1) {
  368. throw new MultiplePagesHitsError(currentPathname);
  369. }
  370. }
  371. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  372. const page = pageWithMeta?.data as unknown as PageDocument;
  373. // add user to seen users
  374. if (page != null && user != null) {
  375. await page.seen(user);
  376. }
  377. // populate & check if the revision is latest
  378. if (page != null) {
  379. page.initLatestRevisionField(revisionId);
  380. props.isLatestRevision = page.isLatestRevision();
  381. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  382. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  383. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  384. }
  385. if (page == null && user != null) {
  386. const templateData = await Page.findTemplate(props.currentPathname);
  387. if (templateData != null) {
  388. props.templateTagData = templateData.templateTags as string[];
  389. props.templateBodyData = templateData.templateBody as string;
  390. }
  391. // apply parent page grant
  392. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  393. if (ancestor != null) {
  394. await applyGrantToPage(props, ancestor);
  395. }
  396. }
  397. props.pageWithMeta = pageWithMeta;
  398. }
  399. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  400. const req: CrowiRequest = context.req as CrowiRequest;
  401. const { crowi } = req;
  402. const Page = crowi.model('Page') as PageModel;
  403. const { currentPathname } = props;
  404. const pageId = getPageIdFromPathname(currentPathname);
  405. const isPermalink = _isPermalink(currentPathname);
  406. const page = props.pageWithMeta?.data;
  407. if (props.isIdenticalPathPage) {
  408. props.isNotCreatable = true;
  409. }
  410. else if (page == null) {
  411. props.isNotFound = true;
  412. props.isNotCreatable = !isCreatablePage(currentPathname);
  413. // check the page is forbidden or just does not exist.
  414. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  415. props.isForbidden = count > 0;
  416. }
  417. else {
  418. props.isNotFound = page.isEmpty;
  419. props.isNotCreatable = false;
  420. props.isForbidden = false;
  421. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  422. if (isPermalink && page.isEmpty) {
  423. props.currentPathname = page.path;
  424. }
  425. // /path/to/page ==> /62a88db47fed8b2d94f30000
  426. if (!isPermalink && !page.isEmpty) {
  427. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  428. if (!isToppage) {
  429. props.currentPathname = `/${page._id}`;
  430. }
  431. }
  432. }
  433. }
  434. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  435. // const req: CrowiRequest = context.req as CrowiRequest;
  436. // const { crowi } = req;
  437. // const UserModel = crowi.model('User');
  438. // if (isUserPage(props.currentPagePath)) {
  439. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  440. // if (user != null) {
  441. // props.pageUser = JSON.stringify(user.toObject());
  442. // }
  443. // }
  444. // }
  445. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  446. const req: CrowiRequest = context.req as CrowiRequest;
  447. const { crowi } = req;
  448. const {
  449. searchService, configManager, aclService,
  450. } = crowi;
  451. props.isSearchServiceConfigured = searchService.isConfigured;
  452. props.isSearchServiceReachable = searchService.isReachable;
  453. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  454. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  455. // props.isMailerSetup = mailService.isMailerSetup;
  456. props.isAclEnabled = aclService.isAclEnabled();
  457. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  458. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  459. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  460. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  461. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  462. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  463. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  464. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  465. props.editorConfig = {
  466. upload: {
  467. isUploadAllFileAllowed: crowi.fileUploadService.getFileUploadEnabled(),
  468. isUploadEnabled: crowi.fileUploadService.getIsUploadable(),
  469. },
  470. };
  471. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  472. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  473. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  474. props.rendererConfig = {
  475. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  476. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  477. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  478. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  479. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  480. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  481. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  482. // XSS Options
  483. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  484. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  485. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  486. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  487. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  488. };
  489. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  490. }
  491. /**
  492. * for Server Side Translations
  493. * @param context
  494. * @param props
  495. * @param namespacesRequired
  496. */
  497. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  498. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  499. props._nextI18Next = nextI18NextConfig._nextI18Next;
  500. }
  501. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  502. const req = context.req as CrowiRequest;
  503. const { user } = req;
  504. const result = await getServerSideCommonProps(context);
  505. // check for presence
  506. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  507. if (!('props' in result)) {
  508. throw new Error('invalid getSSP result');
  509. }
  510. const props: Props = result.props as Props;
  511. if (props.redirectDestination != null) {
  512. return {
  513. redirect: {
  514. permanent: false,
  515. destination: props.redirectDestination,
  516. },
  517. };
  518. }
  519. if (user != null) {
  520. props.currentUser = user.toObject();
  521. }
  522. try {
  523. await injectPageData(context, props);
  524. }
  525. catch (err) {
  526. if (err instanceof MultiplePagesHitsError) {
  527. props.isIdenticalPathPage = true;
  528. }
  529. else {
  530. throw err;
  531. }
  532. }
  533. await injectRoutingInformation(context, props);
  534. injectServerConfigurations(context, props);
  535. await injectNextI18NextConfigurations(context, props, ['translation']);
  536. return {
  537. props,
  538. };
  539. };
  540. export default Page;